/**
 * @Author 韦建韩
 * @Date 2022/4/19
 */
package com.example.devops.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.devops.Manage.ProcessInfoManage;
import com.example.devops.Manage.UserManager.UserInfoManage;
import com.example.devops.dao.MirrorCreateMapper;
import com.example.devops.dao.UserMapper;
import com.example.devops.entity.common.Result;
import com.example.devops.entity.pojo.MirrorInformation;
import com.example.devops.entity.pojo.User;
import com.example.devops.exception.ValidationException;
import com.example.devops.service.IMirrorCreateService;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class MirrorCreateImpl implements IMirrorCreateService {

    @Autowired(required = false)
    MirrorCreateMapper mirrorCreateMapper;
    @Autowired(required = false)
    UserMapper userMapper;

    @Override
    public Result create(MirrorInformation mirrorInformation) {
        User user = UserInfoManage.get();
        Long id = user.getId();
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("name", mirrorInformation.getName());
        MirrorInformation mirrorInformation1 = mirrorCreateMapper.selectOne(queryWrapper);
        if (Objects.nonNull(mirrorInformation1)) {
            throw new ValidationException("该项目名称已存在，请勿重复创建");
        }
        List<Date> publishDate = mirrorInformation.getPublishWindow();
        Date dateStart = publishDate.get(0);
        Long start = dateStart.getTime();
        Date dateEnd = publishDate.get(1);
        Long end = dateEnd.getTime();
        String publishWindow = start.toString() + "-" + end.toString();
        mirrorInformation.setPublishDate(publishWindow);
        mirrorInformation.setUserId(id);
        Long[] numberIds = mirrorInformation.getNumberIds();
        StringBuilder numbers = new StringBuilder();
        for (Long numberId : numberIds) {
            numbers.append(numberId.toString());
            numbers.append("|");
        }
        if(Strings.isNotEmpty(numbers.toString())){
            mirrorInformation.setNumber(numbers.toString());
        }
        mirrorCreateMapper.insert(mirrorInformation);
        return Result.doCreate();
    }

    @Override
    public Result createProcess(String projectName) {
        String infoObject = ProcessInfoManage.getMirrorCreateInfo(projectName);
        return Result.doCreate(infoObject);
    }

    @Override
    public Result getMirrorList() {
        List<MirrorInformation> list = mirrorCreateMapper.getProjectList();
        handleMirrorList(list);
        return Result.doCreate(list);
    }


    public Result getMirrorListById(long id) {
        MirrorInformation list = mirrorCreateMapper.getProjectListById(id);
        List<MirrorInformation> l = new ArrayList<>();
        l.add(list);
        handleMirrorList(l);

        return Result.doCreate(l);
    }

    private void handleDate(MirrorInformation mirrorInformation){
        String publishDateStr = mirrorInformation.getPublishDate();
        if(Objects.isNull(publishDateStr)){
            return;
        }
        String[] publishDate = publishDateStr.split("-");
        //处理时间
        SimpleDateFormat format=new SimpleDateFormat("HH:mm:ss");
        Date start = new Date(Long.parseLong(publishDate[0]));
        Date end = new Date(Long.parseLong(publishDate[1]));
        String startTime = format.format(start);
        String endTime = format.format(end);
        mirrorInformation.setPublishDate(startTime+"-"+endTime);
    }
    private void handleMirrorList(List<MirrorInformation> list) {
        for (MirrorInformation x : list) {
            handleDate(x);
//        list.forEach(x -> {
            String number = x.getNumber();
            if(Objects.isNull(number)){
                continue;
            }
            String[] split = number.split("\\|");
            List<Long> ids = Arrays.stream(split).map(Long::valueOf).collect(Collectors.toList());
            QueryWrapper q = new QueryWrapper();
            q.in("id", ids);
            List<User> list1 = userMapper.selectList(q);
            StringBuilder names = new StringBuilder();
            Iterator<User> iterator = list1.iterator();
            while (iterator.hasNext()) {
                User next = iterator.next();
                names.append(next.getUserName());
                if (iterator.hasNext()) {
                    names.append(",");
                }
            }

            x.setNumber(names.toString());
//        });
    }
    }
    @Override
    public Result deleteMirror(MirrorInformation mirrorInformation) {
        User user = UserInfoManage.get();
        if (!mirrorInformation.getUserId().equals(user.getId())) {
            throw new ValidationException("您没有删除该镜像的权限");
        }
        int i = mirrorCreateMapper.deleteById(mirrorInformation.getId());
        System.out.println(i);
        return Result.doCreate();
    }


}
